import { Button, Card, Input, Form, InputNumber, Select,Radio,Divider,Col,DatePicker} from 'antd';
import { connect} from 'umi';
import React, { useEffect,useState } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from './style.less';
import db from '@/utils/localstorage';
import { value } from 'numeral';
import moment from 'moment';

const FormItem = Form.Item;
const { TextArea } = Input;

const BasicForm = props => {
  const { submitting,dispatch,allVipCard,salesList,shopList,membersList} = props;
  const [form] = Form.useForm();
  const [dictTypeList, setDictTypeList] = useState(db.get("dictTypeList")['payment_method']);
  const [card, setCard] = useState({});
  const [durationDaysMaturity, setDurationDaysMaturity] = useState("");
  const [storedValueAmountMaturity, setStoredValueAmountMaturity] = useState("");
  const [recharge, setRecharge] = useState("");
  useEffect(() => {
    if (dispatch) {
       dispatch({
        type: 'cubeVipBindCard/fetchAllVipCard'
      })

      dispatch({
        type: 'cubeVipBindCard/fetchShopList',
        payload:{
          userId:db.get("user").userId
        }
      })

      dispatch({
        type: 'cubeVipBindCard/fetchSalesList',
        payload:{
          userId:db.get("user").userId
        }
      })
      let memberId=props.location.query.memberId
      if(memberId){
          form.setFieldsValue({memberId:memberId})
          dispatch({
            type: 'cubeVipBindCard/fetchMember',
            payload: {
              id:memberId
            },
          })
      }
     }
   }, []);
  const formItemLayout = {
    labelCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 7,
      },
    },
    wrapperCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 12,
      },
      md: {
        span: 10,
      },
    },
  };
  const submitFormLayout = {
    wrapperCol: {
      xs: {
        span: 24,
        offset: 0,
      },
      sm: {
        span: 10,
        offset: 7,
      },
    },
  };


  const onFinish = async() => {
    const values = await form.validateFields();
    const { dispatch } = props;
    values.cardConsumeType='1';
    if(card.cardType=='1'){
      if(values.storedValueAmount=='customize'){
        values.storedValueAmount = values.storedValueAmountMaturity
      }else{
        let settingPriceGradientDTOList = card.settingPriceGradientDTOList;
        let _settingPriceGradientDTOList = settingPriceGradientDTOList.filter((item)=>item.id==values.storedValueAmount);
        let settingPriceGradientDTO;
        if(_settingPriceGradientDTOList&&_settingPriceGradientDTOList.length>0){
          settingPriceGradientDTO=_settingPriceGradientDTOList[0]
          values.storedValueAmount = settingPriceGradientDTO.storedValueAmount
        }
      }
    }else if(card.cardType=='2'){
      if(values.recharge != 'customize'){
        let settingPriceGradientDTOList = card.settingPriceGradientDTOList;
        let _settingPriceGradientDTOList = settingPriceGradientDTOList.filter((item)=>item.id==values.recharge);
        let settingPriceGradientDTO;
        if(_settingPriceGradientDTOList&&_settingPriceGradientDTOList.length>0){
          settingPriceGradientDTO=_settingPriceGradientDTOList[0]
          values.numberPrivateTeaching = settingPriceGradientDTO.numberPrivateTeaching
          values.numberGroupLessons = settingPriceGradientDTO.numberGroupLessons
          values.numberSmallClasses = settingPriceGradientDTO.numberSmallClasses
        }
      }
    }else if(card.cardType=='3'){
      if(values.cardOpeningTime != '1'){
        values.cardOpeningTime = moment(values.cardOpeningTime).format('YYYY-MM-DD')
      }
      if(values.durationDays=='customize'){
        values.durationDays = values.durationDaysMaturity
      }else{
        let settingPriceGradientDTOList = card.settingPriceGradientDTOList;
        let _settingPriceGradientDTOList = settingPriceGradientDTOList.filter((item)=>item.id==values.durationDays);
        let settingPriceGradientDTO;
        if(_settingPriceGradientDTOList&&_settingPriceGradientDTOList.length>0){
          settingPriceGradientDTO=_settingPriceGradientDTOList[0]
          values.durationDays = settingPriceGradientDTO.durationDays
        }
      }
    }
    console.log('values===>',values)

    dispatch({
      type: 'cubeVipBindCard/add',
      payload: values,
    });
  };

  /**
   * 查询名称或手机号查询会员
   */
  const handleSearch = (value) =>{
    if(value){
      let timeout;
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      function fake() {
        dispatch({
          type: 'cubeVipBindCard/fetchMembersList',
          payload: {
            text:value
          },
        })
      }
      timeout = setTimeout(fake, 500);
    }else{
      dispatch({
        type: 'cubeVipBindCard/common',
        payload: {
          membersList:[]
        },
      });
    }
  }

  const cardChange = (value) =>{
    let cardList=allVipCard.filter((item)=>item.cardId==value);
    let card;    
    if(Array.isArray(cardList)){
      card=cardList[0];
    }
    setCard(card)
    if(card.cardType == '3'){
      if(card.cardSuperSettingsDTO&&card.cardSuperSettingsDTO.isFirstClassOpenCard=='1'){
        form.setFieldsValue({
          cardOpeningTime:'1'
        })
      }
    }
    form.setFieldsValue({
      paidInAmount:''
    })
  }

  const durationDaysChange = e =>{
    let value = e.target.value;
    setDurationDaysMaturity(value)
    if(value != 'customize'){
      let settingPriceGradientDTOList = card.settingPriceGradientDTOList;
      let _settingPriceGradientDTOList = settingPriceGradientDTOList.filter((item)=>item.id==value);
      let settingPriceGradientDTO;
      if(_settingPriceGradientDTOList&&_settingPriceGradientDTOList.length>0){
        settingPriceGradientDTO=_settingPriceGradientDTOList[0]
        form.setFieldsValue({
          paidInAmount:settingPriceGradientDTO.sellingPrice
        })
      }
    }
  }

  const storedValueAmountChange = e =>{
    let value = e.target.value;
    setStoredValueAmountMaturity(value);
    if(value != 'customize'){
      let settingPriceGradientDTOList = card.settingPriceGradientDTOList;
      let _settingPriceGradientDTOList = settingPriceGradientDTOList.filter((item)=>item.id==value);
      let settingPriceGradientDTO;
      if(_settingPriceGradientDTOList&&_settingPriceGradientDTOList.length>0){
        settingPriceGradientDTO=_settingPriceGradientDTOList[0]
        form.setFieldsValue({
          paidInAmount:settingPriceGradientDTO.sellingPrice
        })
      }
    }
  }

  const numberChange = e =>{
    let value = e.target.value;
    setRecharge(value)
    if(value != 'customize'){
      let settingPriceGradientDTOList = card.settingPriceGradientDTOList;
      let _settingPriceGradientDTOList = settingPriceGradientDTOList.filter((item)=>item.id==value);
      let settingPriceGradientDTO;
      if(_settingPriceGradientDTOList&&_settingPriceGradientDTOList.length>0){
        settingPriceGradientDTO=_settingPriceGradientDTOList[0]
        form.setFieldsValue({
          paidInAmount:settingPriceGradientDTO.sellingPrice
        })
      }
    }else{
      form.setFieldsValue({
        paidInAmount:''
      })
    }
  }

  const options = membersList.map(d => <Option key={d.id}>{d.name}({d.phone})</Option>);
  return (
    <PageHeaderWrapper>
       <Form
          style={{
            marginTop: 8,
          }}
          form={form}
          name="basic"
        >
      <Card title="基本信息" style={{marginBottom: 24}} bordered={false}>
          <FormItem
            {...formItemLayout}
            label="会员卡种类"
            name="cardId"
            rules={[
              {
                required: true,
                message: '请选择会员卡种类',
              },
            ]}
          >
            <Select style={{ width: '100%' }} placeholder="请选择" onChange={cardChange}>
              {
                allVipCard&&allVipCard.map((item,index)=> <Select.Option value={item.cardId} key={index}>{item.cardName}</Select.Option>)
              }
            </Select>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="绑定会员"
            name="memberId"
            rules={[
              {
                required: true,
                message: '请选择绑定会员',
              },
            ]}
          >
            <Select
              showSearch
              placeholder="请输入会员姓名或者手机号码"
              showArrow={false}
              filterOption={false}
              onSearch={handleSearch}
              notFoundContent={null}
            >
              {options}
            </Select>
          </FormItem>
      </Card>
      <Card title="会员卡充值" style={{marginBottom: 24}} bordered={false}>
          {
            card.cardType=='1'&&<>
            <FormItem
              {...formItemLayout}
              label="充值元数"
              name="storedValueAmount"
              rules={[
                {
                  required: true,
                  message: '请输入充值元数',
                },
              ]}
            >
               <Radio.Group onChange={storedValueAmountChange}>
                  {
                    card.settingPriceGradientDTOList&&card.settingPriceGradientDTOList.map((item,index)=><Col span={24}><Radio key={index} value={item.id}>
                      <span>储值金额：{item.storedValueAmount}元</span> <Divider type="vertical" />
                      <span>{item.sellingPrice}元</span>
                    </Radio></Col>)
                  }
                  <Col span={24}><Radio value="customize">自定义金额</Radio></Col>  
               </Radio.Group>
            </FormItem>
            {
              storedValueAmountMaturity=='customize'&&<FormItem
              {...formItemLayout}
              label="储值金额/元"
              name="storedValueAmountMaturity"
            >
                <InputNumber
                min={0}
                style={{width:'100%'}}
              />
            </FormItem>
            }
            </>
          }
          {
            card.cardType=='2'&&<>
              <FormItem
                {...formItemLayout}
                label="充值次数"
                name="recharge"
                rules={[
                  {
                    required: true,
                    message: '请输入充值次数',
                  },
                ]}
              >
                <Radio.Group onChange={numberChange}>
                    {
                      card.settingPriceGradientDTOList&&card.settingPriceGradientDTOList.map((item,index)=><Col key={index} span={24}><Radio key={index} value={item.id}>
                        {/* <span>私教次数：{item.numberPrivateTeaching}次</span> <Divider type="vertical" /> */}
                        <span>次数：{item.numberGroupLessons}次</span> 
                        {/* <Divider type="vertical" /> */}
                          {/* <span>小班次数：{item.numberSmallClasses}次</span> */}
                        <Divider type="vertical" /><span>{item.sellingPrice}元</span> <Divider type="vertical" /><span>{item.periodValidity}天内有效</span>
                      </Radio></Col>)
                    }
                    <Col span={24}><Radio value="customize">自定义次数</Radio> </Col> 
                </Radio.Group>
              </FormItem>
              {
                recharge=='customize'&&<>
                {/* <FormItem
                  {...formItemLayout}
                  label="私教次数/次"
                  name="numberPrivateTeaching"
                >
                    <InputNumber
                    placeholder="请输入自定义私教次数"
                    min={0}
                    style={{width:'100%'}}
                  />
                </FormItem> */}
                <FormItem
                  {...formItemLayout}
                  label="次数"
                  name="numberGroupLessons"
                >
                    <InputNumber
                    placeholder="请输入次数"
                    min={0}
                    style={{width:'100%'}}
                  />
                </FormItem>
                {/* <FormItem
                  {...formItemLayout}
                  label="小班次数/次"
                  name="numberSmallClasses"
                >
                    <InputNumber
                    placeholder="请输入自定义小班次数"
                    min={0}
                    style={{width:'100%'}}
                  />
                </FormItem> */}
            </>
            }
            </>
          }
          {
            card.cardType=='3'&&<>
            {
              (card&&card.cardSuperSettingsDTO&&card.cardSuperSettingsDTO.isFirstClassOpenCard=='1')?
                <FormItem
                {...formItemLayout}
                label="开始时间"
                name="cardOpeningTime"
                rules={[
                  {
                    required: true,
                    message: '请选择开始时间',
                  },
                ]}
              >
                <Select style={{ width: '100%' }} placeholder="请选择" disabled>
                  <Select.Option value="1">第一次上课开卡</Select.Option>
                </Select>
              </FormItem>:
              <FormItem
              {...formItemLayout}
              label="开始时间"
              name="cardOpeningTime"
              rules={[
                {
                  required: true,
                  message: '请选择开始时间',
                },
              ]}
            >
              <DatePicker style={{width:'100%'}}/>
            </FormItem>
            }
            <FormItem
              {...formItemLayout}
              label="充值天数"
              name="durationDays"
              rules={[
                {
                  required: true,
                  message: '请输入充值元数',
                },
              ]}
            >
                <Radio.Group onChange={durationDaysChange}>
                  {
                    card.settingPriceGradientDTOList&&card.settingPriceGradientDTOList.map((item,index)=><Col key={index} span={24}><Radio key={index} value={item.id}>
                      <span>期限天数：{item.durationDays}天</span> <Divider type="vertical" />
                      <span>{item.sellingPrice}元</span>
                    </Radio></Col>)
                  }
                  <Col span={24}><Radio value="customize">自定义天数</Radio></Col> 
               </Radio.Group>
            </FormItem>
            {
              durationDaysMaturity=='customize'&&<FormItem
              {...formItemLayout}
              label="期限天数/天"
              name="durationDaysMaturity"
            >
                <InputNumber
                min={0}
                style={{width:'100%'}}
              />
            </FormItem>
            }
            </>
          }
          <FormItem
            {...formItemLayout}
            label="实收金额"
            name="paidInAmount"
            rules={[
              {
                required: true,
                message: '请输入实收金额',
              },
            ]}
          >
            <InputNumber
              min={0}
              style={{width:'100%'}}
              formatter={value => `${value}元`}
              parser={value => value.replace('元', '')}
            />
          </FormItem>
          {/* {
            card.cardType=='1'&&<FormItem
            {...formItemLayout}
            label="折扣"
            name="discount"
            rules={[
              {
                required: true,
                message: '请输入折扣',
              },
            ]}
          >
            <InputNumber
              min={0}
              style={{width:'100%'}}
              formatter={value => `${value}`}
              parser={value => value.replace('', '')}
            />
          </FormItem>
          } */}
          <FormItem
            {...formItemLayout}
            label="支付模式"
            name="paymentMethod"
            rules={[
              {
                required: true,
                message: '请选择支付模式',
              },
            ]}
          >
            <Select style={{ width: '100%' }} placeholder="请选择">
              {
                dictTypeList&&dictTypeList.map((item,index)=><Select.Option key={index} value={item.value}>{item.label}</Select.Option>)
              }
            </Select>
          </FormItem>
          {/* <FormItem
            {...formItemLayout}
            label="开卡场馆"
            name="venueId"
            rules={[
              {
                required: true,
                message: '请选择开卡场馆',
              },
            ]}
          >
             <Select style={{ width: '100%' }} placeholder="请选择">
              {
                shopList&&shopList.map((item,index)=> <Select.Option value={item.id} key={index}>{item.name}</Select.Option>)
              }
            </Select>
          </FormItem> */}
          <FormItem
            {...formItemLayout}
            label="销售人员"
            name="salesStaffId"
            rules={[{ required: true, message: '请选择销售人员' }]}
          >
             <Select style={{ width: '100%' }} placeholder="请选择">
              {
                 salesList&&salesList.map((item,index)=><Select.Option value={item.userId} key={index}>{item.name}</Select.Option>)
              }
            </Select>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="备注信息"
            name="zb"
          >
            <TextArea rows={4} placeholder="请输入"/>
          </FormItem>
          <FormItem
            {...submitFormLayout}
            style={{
              marginTop: 32,
            }}
          >
            <Button type="primary" onClick={onFinish} loading={submitting}>
             提交
            </Button>
            <Button
              style={{
                marginLeft: 8,
              }}
              onClick={()=>window.history.back()}
            >
              返回
            </Button>
          </FormItem>
      </Card>
      </Form>
    </PageHeaderWrapper>
  );
};

export default connect(({ loading,cubeVipBindCard }) => ({
  allVipCard: cubeVipBindCard.allVipCard,
  shopList: cubeVipBindCard.shopList,
  salesList: cubeVipBindCard.salesList,
  membersList: cubeVipBindCard.membersList,
  submitting: loading.effects['cubeVipBindCard/add'],
}))(BasicForm);
